<template>
  <el-card class="box-card">
    <div>{{ currentUser.nickName === '暂未登录' ? currentUser.nickName : currentUser.nickName + '的聊天窗' }}</div>
    <el-input placeholder="账号" v-model="currentUser.username" style="width: 120px;margin: 15px"/>
    <span v-if="currentUser.nickName!=='暂未登录'">当前用户是</span>
    <el-tag v-if="currentUser.nickName!=='暂未登录'">{{ currentUser.nickName }}</el-tag>
    <el-input placeholder="发送" v-model="userText" style="width: 320px;margin: 15px"/>
    <el-button @click="userSendText">发送</el-button>
  </el-card>
  <!-- 内容区域-->
  <el-card style="width: 300px;height: 200px;margin-top: 10px">
    <h3>内容</h3>
    <div v-for="item in showContent">{{item}}</div>
  </el-card>
</template>

<script setup>
import {reactive, ref, watch, toRaw} from 'vue';
import request from "@/utils/request.js";
import {ElMessage, ElNotification} from "element-plus";

const users = ref([
  {
    userId: 1,
    username: 'zhangsan',
    nickName: '张三'
  },
  {
    userId: 2,
    username: 'lisi',
    nickName: '李四'
  }
])
let socket = null;
let currentUser = ref({
  userId: 0,
  username: '',
  nickName: '暂未登录'
});
let showContent=ref([])
watch(() => currentUser.value.username, (value, oldValue) => {
  // 监听当前账号
  if (currentUser.value.username === 'zhangsan') {
    currentUser.value = users.value[0]
    init()
  } else if (currentUser.value.username === 'lisi') {
    currentUser.value = users.value[1]
    init()
  }
})
// 聊天窗文本
const userText = ref('');

function userSendText() {
  // 判断是否登录
  if (currentUser.value.userId === 0) {
    return;
  }
  let user = users.value.filter(item => {
    return item.username !== currentUser.value.username
  })
  let message = {
    fromUserId: currentUser.value.userId,
    toUserId: user[0].userId,
    content: userText.value
  }
  socket.send(JSON.stringify(message))
  ElNotification({
    title: 'Success',
    message: `【${currentUser.value.nickName}】向【${user[0].nickName}】发送消息【${userText.value}】`,
    type: 'success',
  })
}

/**
 * 初始化
 */
function init() {
  if (typeof WebSocket == 'undefined') {
    ElNotification({
      title: 'Error',
      message: `您的浏览器不支持websocket`,
      type: 'error',
    })
    return;
  }
  // 浏览器支持websocket
  let socketUrl = 'ws://localhost:10010/websocket/' + currentUser.value.userId;
  // 开启一个websocket服务
  socket = new WebSocket(socketUrl);
  // 打开事件
  socket.onopen = function () {
    console.log('websocket已经开启');
  }
  // 获得消息事件
  socket.onmessage = function (message) {
    try {
      let {content} = JSON.parse(message.data)
      showContent.value.push(content)
      console.log('websocket收到数据:{}', content);
    } catch (e) {
      console.log("websocket收到数据解析失败:", e);
    }
  }
  // 关闭事件
  socket.onclose = function () {
    console.log('websocket已经关闭');
  }
  // 发生错误
  socket.onerror = function (err) {
    console.log('websocket发生错误:', err);
  }
}

</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
  height: 300px;
}
</style>